import {Component, OnInit, OnChanges, Input, SimpleChanges} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {SystemMgmtServices} from '../http/service';
import {HttpErrorResponse} from '@angular/common/http';

interface DataDictionaryTableItem {
  dictCode: string;
  dictDesc: string;
  createUserName: string;
  createTime: string;
  id?: number;
}

interface DataDictionaryItemTableItem {
  dictCode: string;
  dictDesc: string;
  createUserName: string;
  createTime: string;
  id?: number;
  dictId: number;
  itemName: string;
  itemOrder: number;
  itemValue: string;
  status: string;

}

@Component({
  selector: 'system-data-dictionary',
  styleUrls: ['./components.less'],
  template: `
    <div class="dataMgmtContainer">
      <div class="data-mgmt-bar">
        <div><span>字典码：</span><input nz-input placeholder="输入字典码搜索" [(ngModel)]="keyword"/></div>
        <button nz-button nzType="primary" (click)="loadTableData()">查询</button>
        <button nz-button style="background:'green';color:'#fff';border-color:'transparent'" (click)="createVisible = true">新增</button>
      </div>
      <nz-table #dataDictionaryTable [nzShowSizeChanger]="true" [nzShowQuickJumper]="true"
                [nzData]="tableData" [nzLoading]="loading" [nzFrontPagination]="false"
                [nzTotal]="pagination.total" [(nzPageSize)]="pagination.size" [(nzPageIndex)]="pagination.start"
                (nzPageIndexChange)="pagination.start = $event;loadTableData()"
                (nzPageSizeChange)="pagination.size = $event;loadTableData()">
        <thead>
        <tr>
          <th>字典码</th>
          <th>字典描述</th>
          <th>创建人</th>
          <th>创建时间</th>
          <th nzAlign="center">操作</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let data of dataDictionaryTable.data">
          <td>{{ data.dictCode }}</td>
          <td>{{ data.dictDesc }}</td>
          <td>{{ data.createUserName }}</td>
          <td>{{ data.createTime}}</td>
          <td class='option-td' nzAlign="center">
            <span (click)="editVisible=true;editData=data">修改</span>
            <span (click)="deleteVisible=true;editData=data">删除</span>
          </td>
        </tr>
        </tbody>
      </nz-table>
    </div>

    <nz-modal [(nzVisible)]="createVisible" [nzTitle]="modalTitle" (nzOnCancel)="createVisible = false" (nzOnOk)="onOk()">
      <ng-template #modalTitle>新增字典</ng-template>
      <ng-container *nzModalContent>
        <form nz-form [formGroup]="dictionaryForm">
          <nz-form-item>
            <nz-form-label nzRequired [nzSpan]="4">
              字典码
            </nz-form-label>
            <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
              <input nz-input formControlName="dictCode"/>
            </nz-form-control>
          </nz-form-item>
          <nz-form-item>
            <nz-form-label nzRequired [nzSpan]="4">
              字典描述
            </nz-form-label>
            <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
              <input nz-input formControlName="dictDesc"/>
            </nz-form-control>
          </nz-form-item>
        </form>
      </ng-container>
    </nz-modal>

    <nz-modal [(nzVisible)]="deleteVisible" nzTitle="警告" (nzOnOk)="deleteVisible=false;onDelete()" (nzOnCancel)="deleteVisible=false">
      <ng-container *nzModalContent>
        该操作会将此项中所有关联的数据删除，您确定要继续？
      </ng-container>
    </nz-modal>

    <nz-modal [(nzVisible)]="editVisible" nzTitle="修改数据字典" (nzOnOk)="onEdit()" (nzOnCancel)="editVisible=false" [nzWidth]="888">
      <ng-container *nzModalContent>
        <system-data-dictionary-item [initData]="editData" [originFormGroup]="dictionaryForm"></system-data-dictionary-item>
      </ng-container>
    </nz-modal>
  `
})
export class DataDictionaryComponent implements OnInit {
  constructor(private fb: FormBuilder, private http: SystemMgmtServices) {
  }

  dictionaryForm!: FormGroup;
  createVisible = false;
  deleteVisible = false;
  editVisible = false;
  mode = 'create';
  pagination = {
    start: 1,
    size: 10,
    total: 0
  };
  loading = true;
  keyword = '';
  tableData !: DataDictionaryTableItem[];
  editData !: DataDictionaryTableItem;


  ngOnInit(): void {
    this.loadTableData();
    this.dictionaryForm = this.fb.group({
      dictCode: [null, Validators.required],
      dictDesc: [null, Validators.required]
    });
  }

  loadTableData(): void {
    const {size, start} = this.pagination;
    this.http.queryDD({start: start - 1, size, keyword: this.keyword}).subscribe(
      (response) => {
        if (response.code === 0) {
          this.tableData = response.data.content;
          this.loading = false;
        }
      }, (error: HttpErrorResponse) => {
      }
    );
  }

  onOk(): void {
    this.http.createDD({...this.dictionaryForm.value}).subscribe(
      (response) => {
        if (response.code === 0) {
          this.loadTableData();
          this.createVisible = false;
        }
      }, (error: HttpErrorResponse) => {
      }
    );
  }

  onDelete(): void {
    this.http.deleteDDAndItem(this.editData.id).subscribe(
      (response) => {
        if (response.code === 0) {
          this.loadTableData();
          this.deleteVisible = false;
        }
      }, () => {
      }
    );
  }

  onEdit(): void {
    const {dictCode, dictDesc} = this.dictionaryForm.value;
    const id = this.editData.id;
    this.http.editDD({dictCode, dictDesc, id}).subscribe(
      (response) => {
        if (response.code === 0) {
          this.loadTableData();
          this.editVisible = false;
        }
      }, () => {
      }
    );
  }
}


@Component({
  selector: 'system-data-dictionary-item',
  styleUrls: ['./components.less'],
  template: `
    <div class="data-dictionary-modal">
      <form nz-form [formGroup]="dictionaryEditForm">
        <nz-form-item>
          <nz-form-label nzRequired [nzSpan]="4">
            字典码
          </nz-form-label>
          <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
            <input nz-input formControlName="dictCode"/>
          </nz-form-control>
        </nz-form-item>
        <nz-form-item>
          <nz-form-label nzRequired [nzSpan]="4">
            字典描述
          </nz-form-label>
          <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
            <input nz-input formControlName="dictDesc"/>
          </nz-form-control>
        </nz-form-item>
      </form>
      <br/>
      <button nz-button (click)="itemModalVisible=true">新增</button>
      <div>
        <nz-table #dataDictionaryItemTable [nzShowSizeChanger]="true" [nzShowQuickJumper]="true"
                  [nzData]="itemTableData" [nzLoading]="loading" [nzFrontPagination]="false"
                  [nzTotal]="pagination.total" [(nzPageSize)]="pagination.size" [(nzPageIndex)]="pagination.start"
                  (nzPageIndexChange)="pagination.start = $event;loadItemTable()"
                  (nzPageSizeChange)="pagination.size = $event;loadItemTable()">
          <thead>
          <tr>
            <th>字典项名称</th>
            <th>字典项值</th>
            <th>状态</th>
            <th nzAlign="center">操作</th>
          </tr>
          </thead>
          <tbody>
          <tr *ngFor="let data of dataDictionaryItemTable.data">
            <td>{{ data.itemName }}</td>
            <td>{{ data.itemValue }}</td>
            <td>{{ data.status === '1' ? '启用' : data.status === '2' ? '废止' : '禁止' }}</td>
            <td class='modal-option-td' nzAlign="center">
              <span (click)="onClickEdit(data)">修改</span>
              <span (click)="onDelete(data.id)">删除</span>
            </td>
          </tr>
          </tbody>
        </nz-table>
      </div>
    </div>
    <nz-modal [(nzVisible)]="itemModalVisible" [nzTitle]="modalTitle" (nzOnCancel)="itemModalVisible = false;itemForm.reset()"
              (nzOnOk)="onItemSubmit()">
      <ng-template #modalTitle>{{mode === 'create' ? '新增' : '修改'}}字典项</ng-template>
      <ng-container *nzModalContent>
        <form nz-form [formGroup]="itemForm">
          <nz-form-item>
            <nz-form-label nzRequired [nzSpan]="4">
              字典项名称
            </nz-form-label>
            <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
              <input nz-input formControlName="itemName"/>
            </nz-form-control>
          </nz-form-item>
          <nz-form-item>
            <nz-form-label nzRequired [nzSpan]="4">
              字典项值
            </nz-form-label>
            <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
              <input nz-input formControlName="itemValue"/>
            </nz-form-control>
          </nz-form-item>
          <nz-form-item>
            <nz-form-label nzRequired [nzSpan]="4">
              状态
            </nz-form-label>
            <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
              <nz-select formControlName="status" [nzOptions]="statusDataOption"></nz-select>
            </nz-form-control>
          </nz-form-item>
          <nz-form-item>
            <nz-form-label nzRequired [nzSpan]="4">
              序号
            </nz-form-label>
            <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
              <nz-input-number formControlName="itemOrder" [nzMin]="0"></nz-input-number>
            </nz-form-control>
          </nz-form-item>
        </form>
      </ng-container>
    </nz-modal>
  `
})

export class DataDictionaryItemComponent implements OnInit {
  constructor(private fb: FormBuilder, private http: SystemMgmtServices) {
  }

  @Input() initData: any;
  @Input() originFormGroup: FormGroup;


  dictionaryEditForm!: FormGroup;
  pagination = {
    start: 1,
    size: 10,
    total: 0
  };
  loading = true;

  itemModalVisible = false;
  itemTableData: DataDictionaryItemTableItem[];
  itemEditData: DataDictionaryItemTableItem;
  itemForm!: FormGroup;
  mode = 'create';
  statusDataOption = [{value: '1', label: '启用'}, {value: '2', label: '作废'}, {value: '3', label: '禁止'}];

  ngOnInit(): void {
    this.loadItemTable();
    this.originFormGroup.patchValue(this.initData);
    this.dictionaryEditForm = this.originFormGroup;
    this.itemForm = this.fb.group({
      itemName: [null, Validators.required],
      status: ['1', Validators.required],
      itemValue: [null, Validators.required],
      itemOrder: [0, Validators.required]
    });
  }

  loadItemTable(): void {
    const {size, start} = this.pagination;
    const dictId = this.initData.id;
    this.http.queryDDItem({start: start - 1, size, dictId}).subscribe(
      (response) => {
        if (response.code === 0) {
          this.itemTableData = response.data.content;
          this.pagination.total = response.data.totalElements;
          this.loading = false;
        }
      }, (error: HttpErrorResponse) => {
      }
    );
  }

  onItemSubmit(): void {
    const {itemName, itemValue, itemOrder, status} = this.itemForm.value;
    const dictId = this.initData.id;
    if (this.mode === 'create') {
      this.http.createDDItem({itemName, itemValue, itemOrder, status, dictId}).subscribe(
        (response) => {
          if (response.code === 0) {
            this.loadItemTable();
            this.itemModalVisible = false;
            this.itemForm.reset();
          }
        }, () => {
        }
      );
    } else {
      const {id} = this.itemEditData;
      this.http.editDDItem({itemName, itemValue, itemOrder, status, dictId, id}).subscribe(
        (response) => {
          if (response.code === 0) {
            this.loadItemTable();
            this.itemModalVisible = false;
            this.mode = 'create';
            this.itemForm.reset();
          }
        }, () => {
        }
      );

    }
  }

  onClickEdit(data): void {
    this.mode = 'edit';
    this.itemModalVisible = true;
    this.itemEditData = data;
    this.itemForm.patchValue(data);
  }

  onDelete(id): void {
    this.http.deleteDDItem(id).subscribe(
      (response) => {
        if (response.code === 0) {
          this.loadItemTable();
        }
      }, () => {
      }
    );
  }
}
